package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import VideoHandle.EpDraw;
import VideoHandle.EpEditor;
import VideoHandle.EpVideo;
import VideoHandle.OnEditorListener;
import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.ColorAdapter;
import flc.ast.bean.MyColorBean;
import flc.ast.databinding.ActivityVideoTextBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;
import stark.common.basic.view.container.StkRelativeLayout;

public class VideoTextActivity extends BaseAc<ActivityVideoTextBinding> {

    public static String videoPath;
    private long videoLength;
    private ColorAdapter colorAdapter;
    private int oldPosition;
    private int videoWidth, videoHeight;

    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvPlayLeft.setText(TimeUtil.getMmss(mDataBinding.videoView.getCurrentPosition()));
            mHandler.postDelayed(this, 500);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.activity_video_text;
    }

    @Override
    protected void initView() {
        mDataBinding.ivVideoTextBack.setOnClickListener(v -> onBackPressed());
        mDataBinding.ivPlayStart.setOnClickListener(this);
        mDataBinding.ivPlayFull.setOnClickListener(this);
        mDataBinding.ivVideoTextSave.setOnClickListener(this);
        mDataBinding.ivConfirm.setOnClickListener(this);
        //文字
        mDataBinding.rvVideoTextColorList.setLayoutManager(new GridLayoutManager(mContext, 8));
        colorAdapter = new ColorAdapter();
        mDataBinding.rvVideoTextColorList.setAdapter(colorAdapter);
        colorAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPlayStart://播放
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.abofang);
                    mDataBinding.videoView.pause();
                } else {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.ivPlayFull://放大
                PlayActivity.videoUri = videoPath;
                startActivity(PlayActivity.class);
                break;
            case R.id.ivConfirm://添加文字
                KeyboardUtils.hideSoftInput(this);
                if (TextUtils.isEmpty(mDataBinding.etTextContent.getText().toString())) {
                    ToastUtils.showShort(R.string.please_input_text);
                    return;
                }
                mDataBinding.txtStickerView.setText(mDataBinding.etTextContent.getText().toString());
                break;
            case R.id.ivVideoTextSave://保存
                mDataBinding.txtStickerView.setShowHelpBox(false);
                save();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        colorAdapter.getItem(oldPosition).setSelect(false);
        colorAdapter.notifyItemChanged(oldPosition);
        oldPosition = position;
        colorAdapter.getItem(position).setSelect(true);
        colorAdapter.notifyItemChanged(position);
        mDataBinding.txtStickerView.setTextColor(Color.parseColor(colorAdapter.getItem(position).getColor()));
    }

    @Override
    protected void initData() {
        videoLength = MediaUtil.getDuration(videoPath);
        //设置播放器
        setPlayer();
        setSticker();
        //文字
        List<MyColorBean> listColor = new ArrayList<>();
        listColor.add(new MyColorBean("#000000", true));
        listColor.add(new MyColorBean("#FFFFFF", false));
        listColor.add(new MyColorBean("#E12D2D", false));
        listColor.add(new MyColorBean("#FFA8A8", false));
        listColor.add(new MyColorBean("#FFB652", false));
        listColor.add(new MyColorBean("#FFF62C", false));
        listColor.add(new MyColorBean("#79BA56", false));
        listColor.add(new MyColorBean("#35B9B0", false));
        listColor.add(new MyColorBean("#3F68BC", false));
        listColor.add(new MyColorBean("#9F45F1", false));
        listColor.add(new MyColorBean("#E85C90", false));
        listColor.add(new MyColorBean("#C0C0C0", false));
        listColor.add(new MyColorBean("#CA58C9", false));
        listColor.add(new MyColorBean("#8A72E1", false));
        listColor.add(new MyColorBean("#46D5AF", false));
        listColor.add(new MyColorBean("#5E8C4F", false));
        colorAdapter.setList(listColor);
        mDataBinding.txtStickerView.setTextColor(Color.parseColor("#000000"));
    }

    //设置播放器
    private void setPlayer() {
        mHandler = new Handler();
        mDataBinding.tvPlayLeft.setText("00:00");
        mDataBinding.tvPlayRight.setText(" / " + TimeUtil.getMmss(videoLength));
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mDataBinding.tvPlayLeft.setText("00:00");
                mDataBinding.ivPlayStart.setImageResource(R.drawable.abofang);
                mDataBinding.videoView.seekTo(1);
                stopTime();
            }
        });
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
        mDataBinding.videoView.start();
        startTime();
    }

    //保存
    private void save() {
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            private String imagePath;

            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                Bitmap bitmap = ImageUtils.view2Bitmap(mDataBinding.txtStickerView);
                imagePath = FileUtil.generateFilePath(Content.myTemp, ".png");
                boolean save = ImageUtils.save(bitmap, imagePath, Bitmap.CompressFormat.PNG);
                emitter.onNext(save);
            }

            @Override
            public void accept(Boolean isSave) {
                if (isSave) {
                    EpDraw epDraw = new EpDraw(imagePath, 0, 0, videoWidth, videoHeight, false);
                    epDraw.setRotate(0);
                    String resultFile = FileUtil.generateFilePath(Content.myTemp, ".mp4");//保存到我的视频
                    EpVideo epVideo = new EpVideo(videoPath);
                    epVideo.addDraw(epDraw);
                    EpEditor.OutputOption outputOption = new EpEditor.OutputOption(resultFile);
                    EpEditor.exec(epVideo, outputOption, new OnEditorListener() {
                        @Override
                        public void onSuccess() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    dismissDialog();
                                    ToastUtils.showShort(R.string.save_success);
                                    FileP2pUtil.copyPrivateVideoToPublic(mContext, resultFile);
                                    startActivity(HomeActivity.class);
                                }
                            });
                        }

                        @Override
                        public void onFailure() {
                            dismissDialog();
                            ToastUtils.showShort(R.string.text_def);
                        }

                        @Override
                        public void onProgress(float progress) {
                            float v = progress * 100;
                            if (v < 0) {
                                v = 0;
                            } else if (v > 100) {
                                v = 100;
                            }
                            showDialog(getString(R.string.text_ing)
                                    + new DecimalFormat("#.0").format(v) + "%");
                        }
                    });
                }
            }
        });
    }

    //设置贴纸
    private void setSticker() {
        // 获取videoView真实的宽高大小
        mDataBinding.videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                videoWidth = mp.getVideoWidth();
                videoHeight = mp.getVideoHeight();
            }
        });
        // 将stickerView的宽高大小设置成videoView一样的大小
        mDataBinding.videoView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                StkRelativeLayout.LayoutParams stickerLayoutParams = (StkRelativeLayout.LayoutParams) mDataBinding.txtStickerView.getLayoutParams();
                stickerLayoutParams.width = right - left;
                stickerLayoutParams.height = bottom - top;
                mDataBinding.txtStickerView.setLayoutParams(stickerLayoutParams);
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopTime();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
        mDataBinding.videoView.start();
        startTime();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FileUtils.delete(PathUtils.getFilesPathExternalFirst() + Content.myTemp);
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

}